package com.liuym.login.controller;

import com.liuym.common.constants.GradeResponse;
import com.liuym.common.exception.LoginException;
import com.liuym.common.exception.StudentException;
import com.liuym.login.repository.model.bo.LoginUserBO;
import com.liuym.login.repository.model.vo.LoginResponseVO;
import com.liuym.login.repository.model.vo.LoginUserVO;
import com.liuym.login.service.LoginService;
import com.vip.vjtools.vjkit.mapper.BeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author LiuYiMing
 * @date 2018/9/18 11:44
 * @describe：
 */
@RestController
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public GradeResponse login(LoginUserVO loginUserVO,
                               @RequestParam(value = "role") String role) throws StudentException {
        String token = "";
        // conductResponse = baseParamCheck(studentVO);.
        try {
            LoginResponseVO vo = new LoginResponseVO();
            token = loginService.login(BeanMapper.map(loginUserVO, LoginUserBO.class), role);
            vo.setToken(token);
            return GradeResponse.success(vo);
        } catch (Exception e) {
            if (e instanceof LoginException) {
                logger.warn("error", e);
                return GradeResponse.fail(((LoginException) e).getCode(), ((LoginException) e).getMsg());
            } else {
                return GradeResponse.internalServerError();
            }
        }
    }

    @RequestMapping("/testSession")
    public String testSession(HttpServletRequest request) {
        request.getSession().setAttribute("requestUrl", "123");
        String attribute = (String) request.getSession().getAttribute("requestUrl");
        return attribute;
    }
}
